<template>
  <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="visible" class="cu-dialog cu-dialog_center" lock-scroll width="800px">
    <el-form ref="elForm" :model="dataForm" size="medium" label-width="100px" label-position="right" :rules="rules" label-with="110px">
      <el-col :span="12">
        <el-form-item label="咨询人" prop="name">
          <el-input v-model="dataForm.name" placeholder="请输入" clearable required :style="{ width: '100%' }"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="性别" prop="gender">
          <el-select v-model="dataForm.gender" placeholder="请选择性别" clearable :style="{ width: '100%' }">
            <el-option v-for="(item, index) in genderOptions" :key="index" :label="item.fullName" :value="item.enCode"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="省市区" prop="area">
          <custom-address v-model="dataForm.area" placeholder="请选择所在地区" clearable required :checkStrictly="true" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="dataForm.address" placeholder="请输入" clearable required :style="{ width: '100%' }"></el-input>
        </el-form-item>
      </el-col>
      <!-- <el-col :span="12">
        <el-form-item label="联系方式" prop="contactType">
          <el-select v-model="dataForm.contactType" placeholder="选择联系方式" clearable required :style="{ width: '100%' }">
            <el-option label="电话" value="phone" />
            <el-option label="微信" value="wechat" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
      </el-col> -->
      <el-col :span="12">
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="dataForm.mobile" placeholder="请输入" clearable required :style="{ width: '100%' }"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="微信" prop="wechat">
          <el-input v-model="dataForm.wechat" placeholder="请输入" clearable required :style="{ width: '100%' }"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="dataForm.id == ''">
        <el-form-item label="咨询时间" prop="time">
          <el-date-picker v-model="dataForm.time" placeholder="请选择" clearable required :style="{ width: '100%' }" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="timestamp"></el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="dataForm.id == ''">
        <el-form-item label="咨询渠道" prop="channel">
          <el-select v-model="dataForm.channel" placeholder="请选择" clearable required :style="{ width: '100%' }" filterable @change="handleChangeChannel">
            <el-option-group v-for="group in channelOptions" :key="group.id" :label="group.fullName">
              <el-option v-for="item in group.children" :key="item.id" :label="item.fullName" :value="item.enCode"></el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="dataForm.id == ''">
        <el-form-item label="咨询内容" prop="content">
          <el-input v-model="dataForm.content" placeholder="请输入" required show-word-limit :style="{ width: '100%' }" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24" v-if="dataForm.id == ''">
        <el-form-item label="聊天截图" prop="chatScreen">
          <custom-upload-img v-model="dataForm.chatScreen" :fileSize="5" sizeUnit="MB" :limit="9" type="consult"></custom-upload-img>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="客户类别" prop="category">
          <!-- <custom-tree-select v-model="dataForm.category" placeholder="请选择" :option="categoryOptions" lastLevel clearable required :style="{ width: '100%' }" filterable></custom-tree-select> -->
          <custom-tree-select
            v-model="dataForm.category"
            :options="categoryOptions"
            placeholder="请选择"
            lastLevel
            clearable
            required
            :props="{
              value: 'enCode', // ID字段名
              label: 'fullName', // 显示名称
              children: 'children', // 子级字段名
              disabled: 'selectable'
            }"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="年龄段" prop="age">
          <el-select v-model="dataForm.age" placeholder="请选择" clearable required :style="{ width: '100%' }">
            <el-option v-for="(item, index) in ageOptions" :key="item.id" :label="item.fullName" :value="item.enCode"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="关注重点" prop="focusAttention">
          <el-select v-model="dataForm.focusAttention" placeholder="请选择" required multiple clearable :style="{ width: '100%' }">
            <el-option v-for="(item, index) in focusAttentionOptions" :key="item.id" :label="item.fullName" :value="item.enCode"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="意向学校" prop="schools">
          <el-input v-model="dataForm.schools" placeholder="请输入意向小学/中学" required clearable :style="{ width: '100%' }"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="情况概述" prop="followupSummary">
          <el-input v-model="dataForm.followupSummary" type="textarea" :rows="6" />
        </el-form-item>
      </el-col>
    </el-form>
    <!-- </el-row> -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('common.cancelButton') }}</el-button>
      <el-button type="primary" @click="dataFormSubmit()" :loading="loading">
        {{ $t('common.confirmButton') }}
      </el-button>
    </span>
  </el-dialog>
</template>
<script>
import { createCustomer, updateCustomer, getCustomerInfo } from '@/api/crm/customer'
import { getSchoolSelector } from '@/api/crm/school'
export default {
  components: {},
  props: [],
  data() {
    return {
      loading: false,
      visible: false,
      title: undefined,
      dataForm: {
        id: undefined,
        name: undefined,
        address: undefined,
        area: [],
        mobile: undefined,
        wechat: undefined,
        contactType: 'phone',
        managerId: undefined,
        time: undefined,
        channel: undefined,
        channelName: undefined,
        content: undefined,
        chatScreen: [],
        gender: undefined,
        age: undefined,
        schools: undefined,
        status: '1',
        category: undefined,
        focusAttention: undefined,
        followupSummary: undefined
      },
      defaultProps: {
        value: 'enCode',
        children: 'children',
        label: 'fullName',
        disabled: 'selectable'
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入客户姓名',
            trigger: 'blur'
          }
        ],
        area: [
          {
            required: true,
            message: '请选择省市区',
            trigger: 'change'
          }
        ],
        contactType: [
          {
            required: true,
            message: '请选择联系方式类型',
            trigger: 'change'
          }
        ],
        mobile: [
          {
            // required: true,
            pattern: /^1[3456789]\d{9}$|^0\d{2,3}-?\d{7,8}$/,
            message: '请输入正确的联系方式',
            trigger: 'blur'
          },
          { validator: this.validateWechatOrMobile, trigger: 'blur' }
        ],
        wechat: [{ validator: this.validateWechatOrMobile, trigger: 'blur' }],
        age: [
          {
            required: true,
            message: '请选择客户年龄段',
            trigger: 'blur'
          }
        ],
        managerId: [
          {
            required: true,
            message: '请选择招商经理',
            trigger: 'blur'
          }
        ],
        time: [
          {
            required: true,
            message: '请输入咨询时间',
            trigger: 'change'
          }
        ],
        channel: [
          {
            required: true,
            message: '请输入咨询渠道',
            trigger: 'change'
          }
        ],
        category: [
          {
            required: true,
            message: '请选择客户类别',
            trigger: 'change'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入咨询内容',
            trigger: 'blur'
          }
        ],
        focusAttention: [
          {
            required: true,
            message: '请选择客户关注的重点',
            trigger: 'blur'
          }
        ],
        followupSummary: [
          {
            required: true,
            message: '请输入客户的跟进情况概述',
            trigger: 'blur'
          }
        ]
      },
      channelOptions: [],
      businessOptions: [],
      schoolsOptions: [],
      genderOptions: [],
      ageOptions: [],
      categoryOptions: [],
      focusAttentionOptions: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getChannelOptions()
    this.getGenderOptions()
    this.getCategoryOptions()
    this.getAgeOptions()
    this.getFocusAttentionOptions()
  },
  mounted() {},
  methods: {
    validateWechatOrMobile(rule, value, callback) {
      if (!value && !this.dataForm.mobile && !this.dataForm.wechat) {
        callback(new Error('联系电话和微信不能同时为空'))
      } else {
        callback()
      }
    },
    getFocusAttentionOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'FocusAttention' }).then(res => {
        this.focusAttentionOptions = res.filter(o => o.enabledMark == 1)
      })
    },

    getChannelOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'ConsultChannels' }).then(res => {
        this.channelOptions = res.filter(o => o.enabledMark == 1)
      })
    },
    getCategoryOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'CustomerCategory' }).then(res => {
        this.categoryOptions = res.filter(o => o.enabledMark == 1)
      })
    },
    getAgeOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'CustomerAge' }).then(res => {
        this.ageOptions = res.filter(o => o.enabledMark == 1)
      })
    },
    handleChangeChannel(val) {
      let that = this
      //   this.dataForm.consultChannelName = this.dataForm.consultChannel | this.dynamicCodeText(this.channelOptions)
      this.channelOptions.forEach(item => {
        item['children'].forEach(children => {
          if (children.enCode == val) {
            that.dataForm.consultChannelName = children.fullName
          }
        })
      })
    },
    getGenderOptions() {
      this.$store.dispatch('base/getDictionaryData', { sort: 'sex' }).then(res => {
        this.genderOptions = res.filter(o => o.enabledMark == 1)
      })
    },
    querySearchSchoolAsync(queryString, cb) {
      getSchoolSelector(this.dataForm.area.join(), queryString, 'primary').then(res => {
        cb(res.data)
      })
    },
    init(id, status) {
      this.dataForm.id = id || ''
      this.title = !this.dataForm.id ? '新建' : '编辑'
      this.dataForm.status = !this.dataForm.id ? '1' : status
      if (status == 3) {
        this.title += '-重点客户'
      }
      this.dataForm.consultTime = +new Date()
      this.visible = true
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
        if (this.dataForm.id) {
          getCustomerInfo(this.dataForm.id).then(res => {
            this.dataForm = res.data
            if (res.data.mobile != null) {
              this.dataForm.contactType = 'phone'
            } else if (res.data.wechat != null) {
              this.dataForm.contactType = 'wechat'
            }
            this.dataForm.status = !status ? res.data.status : status
          })
        }
      })
    },
    handleSelectSchool(item) {
      this.dataForm.schools = item.name
    },
    dataFormSubmit() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          this.loading = true
          const formMethod = this.dataForm.id ? updateCustomer : createCustomer
          formMethod(this.dataForm)
            .then(res => {
              this.$message({
                message: res.data + '' + res.msg,
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.visible = false
                  this.loading = false
                  this.$refs['elForm'].resetFields()
                  this.$emit('refresh')
                }
              })
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>
